package com.lysj.bhp.api.controller;

import com.lysj.bhp.api.base.ApiContent;
import com.lysj.bhp.coinexchange.domain.BhpcRecord;
import com.lysj.bhp.coinexchange.dto.BhpcRecordDto;
import com.lysj.bhp.coinexchange.vo.BhpcRecordVo;
import com.lysj.bhp.exchangerate.vo.MyBalanceVo;
import com.lysj.bhp.recharge.domain.RechargeRecord;
import com.lysj.bhp.util.random.FormatUtil;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import com.lysj.bhp.wallet.domain.BhpcWallet;
import com.lysj.bhp.wallet.domain.BitCoinWallet;
import com.lysj.bhp.wallet.domain.EthereumWallet;
import com.lysj.bhp.wallet.vo.WalletVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/v2/user")
@Api(value = "ApiFinancialController", tags = "我的理财接口模块")
public class ApiFinancialController extends ApiContent {

    @InitBinder
    public void InitBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    //查询理财记录
    @ApiOperation(value = "理财记录", notes = "查询条件起始时间,type,10:比特币;20:以太坊;100:BHPC;")
    @PostMapping("/financial_list")
    public Resp financialList(BhpcRecordDto model) {
        //查询条件数据为空,进行初始化操作
        if (ParamUtil.isBlack(model.getLimit())) {
            model.setLimit(5);
        }
        if (ParamUtil.isBlack(model.getPage())) {
            model.setPage(0);
        }
        if (model.getBegin_createDate() == null) {
            model.setBegin_createDate(FormatUtil.addDay(new Date(), -30));
        } else {
            model.setBegin_createDate(FormatUtil.getDayStartDay(model.getBegin_createDate()));
        }
        if (model.getEnd_createDate() == null) {
            model.setEnd_createDate(FormatUtil.getDayEndDay(new Date())); //  获取到今天的结束
        } else {
            model.setEnd_createDate(FormatUtil.getDayEndDay(model.getEnd_createDate()));
        }
//        if (ParamUtil.isBlack(model.getType())) {
//            model.setType(10);
//        }

        //获取根据时间以及币种查询出的充值记录
        Pageable pageable = new PageRequest(model.getPage(), model.getLimit(), new Sort(Sort.Direction.DESC, "createDate"));
        model.setUserId(currentUser().getUserId());// 当前登录用户的充值记录
        Specification specification = ParamUtil.createSpecification(model);
        Page<BhpcRecord> bhpcRecordPagepage = bhpcRecordRepository.findAll(specification, pageable);
        List<BhpcRecordVo> bhpcRecordVos = new LinkedList<BhpcRecordVo>();
        for (BhpcRecord bhpcRecord : bhpcRecordPagepage.getContent()) {
            BhpcRecordVo bhpcRecordVo = new BhpcRecordVo();
            bhpcRecordVo.setExchangeNum(bhpcRecord.getExchangeNum().setScale(6, BigDecimal.ROUND_DOWN));
            bhpcRecordVo.setRealNum(bhpcRecord.getBhpc());
            bhpcRecordVo.setExchangeCost(BigDecimal.valueOf(0));
            bhpcRecordVo.setState("成功");
            bhpcRecordVo.setCreateDate(bhpcRecord.getCreateDate());
            if(200==bhpcRecord.getType()){
                bhpcRecordVo.setExchangeCurrency("Dividend ETH");
                bhpcRecordVo.setTargetCurrency("BHPC");
            }else{
                bhpcRecordVo.setExchangeCurrency(bhpcRecord.getType() == 10 ? "BTC" : "ETH");
                bhpcRecordVo.setTargetCurrency("BHPC");
            }
            bhpcRecordVos.add(bhpcRecordVo);
        }

        Map<String, Object> respMap = new HashMap();
        respMap.put("totalpage", bhpcRecordPagepage.getTotalPages());
        respMap.put("rows", bhpcRecordVos);
        return new Resp(respMap);
    }

    @ApiOperation(value = "实际金额", notes = "需要币种类型,数量")
    @PostMapping("/actual_amount")
    public Resp actualAmount(int type, BigDecimal num) {
        if (null == num || num.compareTo(BigDecimal.valueOf(0)) == 0) {
            return new Resp(Resp.PARAM_ERROR, "数量不能为空");
        }
        if (num.compareTo(BigDecimal.valueOf(0)) == -1) {
            return new Resp(Resp.PARAM_ERROR, "请输入正确的数量");
        }

        BigDecimal bhpcNum = BigDecimal.valueOf(0);
        if (type == 10) {
            BigDecimal DollarNum = num.multiply(exchangeRate.getBITCOIN_TO_DOLLAR());
            bhpcNum = DollarNum.divide(exchangeRate.getBHPC_TO_DOLLAR(), 6, BigDecimal.ROUND_DOWN);
        } else if (type == 20||type==200) {
            BigDecimal DollarNum = num.multiply(exchangeRate.getETHEREUM_TO_DOLLAR());
            bhpcNum = DollarNum.divide(exchangeRate.getBHPC_TO_DOLLAR(), 6, BigDecimal.ROUND_DOWN);
        } else {
            return new Resp(Resp.PARAM_ERROR, "币种类型错误");
        }
        Map<String, Object> map = new HashMap<>();
        //构建一个Vo,显示总资产跟算力币兑换比特币跟ETH汇率
        MyBalanceVo myBalanceVo = new MyBalanceVo();
        myBalanceVo.setBhpc2btc(exchangeRate.getBHPC_TO_DOLLAR().divide(exchangeRate.getBITCOIN_TO_DOLLAR(), 6, BigDecimal.ROUND_DOWN));
        myBalanceVo.setBhpc2eth(exchangeRate.getBHPC_TO_DOLLAR().divide(exchangeRate.getETHEREUM_TO_DOLLAR(), 6, BigDecimal.ROUND_DOWN));
        map.put("myBalanceVo", myBalanceVo);
        map.put("bhpcNum", bhpcNum);
        return new Resp(map);
    }

    @ApiOperation(value = "购买BHPC", notes = "需要兑换数量,交易密码,钱包类型type:10:比特币;20:以太坊;100:BHPC")
    @PostMapping("/buy_bhpc")
    public Resp buyBhpc(BhpcRecord model, int type, String password) throws Exception {
//        if (!isAllIco) {
//            return new Resp(Resp.PARAM_ERROR, "暂时还没有开放购买，请您关注我们官网的动态");
//        }
        return applyService.buyBhpcByUser(model, type, password);
    }

    @ApiOperation(value = "进入币币理财界面显示的信息", notes = "")
    @GetMapping("/bhpc_manage")
    public Resp buyBhpc() {
        Map<String, Object> map = new HashMap<>();
        //获取用户的所有钱包
        BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(currentUser().getUserId());
        EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(currentUser().getUserId());
//        BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(currentUser().getUserId());
        //创建返回的钱包
        List<WalletVo> walletVos = new LinkedList<>();
        WalletVo bitcoinWallteVo = new WalletVo();
        WalletVo ethereumWalletVo = new WalletVo();
//        WalletVo bhpcWalletVo = new WalletVo();
        bitcoinWallteVo.setType(10);
        bitcoinWallteVo.setName("BTC");
        bitcoinWallteVo.setChineseName("比特币");
        ethereumWalletVo.setType(20);
        ethereumWalletVo.setName("ETH");
        ethereumWalletVo.setChineseName("以太坊");
//        bhpcWalletVo.setType(100);
//        bhpcWalletVo.setName("BHPC");
//        bhpcWalletVo.setChineseName("算力现金");
        if (null != bitCoinWallet) {
            bitcoinWallteVo.setAvailBalance(bitCoinWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
        } else {
            bitcoinWallteVo.setAvailBalance(new BigDecimal(BigInteger.ZERO));
        }
        if (null != ethereumWallet) {
            ethereumWalletVo.setAvailBalance(ethereumWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
        } else {
            ethereumWalletVo.setAvailBalance(new BigDecimal(BigInteger.ZERO));
        }
//        if (null != bhpcWallet) {
//            bhpcWalletVo.setAvailBalance(bhpcWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
//        } else {
//            bhpcWalletVo.setAvailBalance(new BigDecimal(BigInteger.ZERO));
//        }
        //---------------------计算用户钱包中价值最大的--------------------------------------------
        BigDecimal btc = bitcoinWallteVo.getAvailBalance().multiply(exchangeRate.getBITCOIN_TO_DOLLAR());
        BigDecimal eth = ethereumWalletVo.getAvailBalance().multiply(exchangeRate.getETHEREUM_TO_DOLLAR());
//        BigDecimal bhpc = bhpcWalletVo.getAvailBalance().multiply(exchangeRate.getBhpcToDollar());
        BigDecimal max = new BigDecimal(BigInteger.ZERO);
        bitcoinWallteVo.setDollarAvailBalance(btc);
        ethereumWalletVo.setDollarAvailBalance(eth);
//        bhpcWalletVo.setDollarAvailBalance(bhpc);
        max = (btc.compareTo(eth) == 1) ? btc : eth;
//        max = (bhpc.compareTo(max) == 1) ? bhpc : max;
        walletVos.add(bitcoinWallteVo);
        walletVos.add(ethereumWalletVo);
//        walletVos.add(bhpcWalletVo);
        for (WalletVo walletVo : walletVos) {
            if (walletVo.getDollarAvailBalance().compareTo(max) == 0) {
                map.put("maxValue", walletVo.getChineseName());
                break;
            }
        }
        map.put("walletVos", walletVos);
        //获取最新5条充值记录
        Pageable pageable = new PageRequest(0, 5);
        List<BhpcRecord> bhpcRecordList = bhpcRecordRepository.findByUserIdAndTypeNotInOrderByCreateDateDesc(currentUser().getUserId(),200, pageable);
        List<BhpcRecordVo> bhpcRecordVos = new LinkedList<BhpcRecordVo>();
        for (BhpcRecord bhpcRecord : bhpcRecordList) {
            BhpcRecordVo bhpcRecordVo = new BhpcRecordVo();
            bhpcRecordVo.setExchangeNum(bhpcRecord.getExchangeNum().setScale(6, BigDecimal.ROUND_DOWN));
            bhpcRecordVo.setRealNum(bhpcRecord.getBhpc());
            bhpcRecordVo.setExchangeCost(BigDecimal.valueOf(0));
            bhpcRecordVo.setState("成功");
            bhpcRecordVo.setCreateDate(bhpcRecord.getCreateDate());
            if(200==bhpcRecord.getType()){
                bhpcRecordVo.setExchangeCurrency("Dividend ETH");
                bhpcRecordVo.setTargetCurrency("BHPC");
            }else{
                bhpcRecordVo.setExchangeCurrency(bhpcRecord.getType() == 10 ? "BTC" : "ETH");
                bhpcRecordVo.setTargetCurrency("BHPC");
            }
            bhpcRecordVos.add(bhpcRecordVo);
        }
        map.put("lastBhpcRecordList", bhpcRecordVos);

        //构建一个Vo,显示总资产跟算力币兑换比特币跟ETH汇率
        MyBalanceVo myBalanceVo = new MyBalanceVo();
        myBalanceVo.setBhpc2btc(exchangeRate.getBHPC_TO_DOLLAR().divide(exchangeRate.getBITCOIN_TO_DOLLAR(), 6, BigDecimal.ROUND_DOWN));
        myBalanceVo.setBhpc2eth(exchangeRate.getBHPC_TO_DOLLAR().divide(exchangeRate.getETHEREUM_TO_DOLLAR(), 6, BigDecimal.ROUND_DOWN));
        map.put("myBalanceVo", myBalanceVo);
        return new Resp(map);
    }


    @ApiOperation(value = "利息兑换奖励金", notes = "需要token,兑换数量,交易密码,兑换类型;参数:token,exchangeNum,tradePassword,type:200利息兑换奖励金;")
    @PostMapping("/divide_exchange_bhpc_bouns")
    public Resp exchangeBhpcBouns(BigDecimal exchangeNum, int type, String tradePassword) {

        return exchangeBhpcBounsService.exchangeBhpcBouns(exchangeNum, type, tradePassword);
    }


    @ApiOperation(value = "利息兑换奖励金界面显示的信息", notes = "")
    @GetMapping("/bhpc_bouns_manage")
    public Resp bhpcBounsManage() {
        Map<String, Object> map = new HashMap<>();

        //获取最新5条利息兑换
        Pageable pageable = new PageRequest(0, 5);
        List<BhpcRecord> bhpcRecordList = bhpcRecordRepository.findByUserIdAndTypeOrderByCreateDateDesc(currentUser().getUserId(), 200, pageable);
        List<BhpcRecordVo> bhpcRecordVos = new LinkedList<BhpcRecordVo>();
        for (BhpcRecord bhpcRecord : bhpcRecordList) {
            BhpcRecordVo bhpcRecordVo = new BhpcRecordVo();
            bhpcRecordVo.setExchangeCurrency("Dividend ETH");
            bhpcRecordVo.setExchangeNum(bhpcRecord.getExchangeNum().setScale(6, BigDecimal.ROUND_DOWN));
            bhpcRecordVo.setTargetCurrency("BHPC");
            bhpcRecordVo.setRealNum(bhpcRecord.getBhpc());
            bhpcRecordVo.setExchangeCost(BigDecimal.valueOf(0));
            bhpcRecordVo.setState("成功");
            bhpcRecordVo.setCreateDate(bhpcRecord.getCreateDate());
            bhpcRecordVos.add(bhpcRecordVo);
        }
        WalletVo walletVo=new WalletVo();
        walletVo.setName("Dividend ETH");
        walletVo.setChineseName("利息 ETH");
        walletVo.setAvailBalance(currentUser().getDividend().setScale(6,BigDecimal.ROUND_DOWN));
        walletVo.setType(200);
        map.put("lastBhpcRecordList", bhpcRecordVos);
        map.put("walletVos", walletVo);
        map.put("bhpc2eth", exchangeRate.getBHPC_TO_DOLLAR().divide(exchangeRate.getETHEREUM_TO_DOLLAR(), 6, BigDecimal.ROUND_DOWN));
        return new Resp(map);
    }

}
